package models

import (
	"lao-a/helper"
)

// SEQ_ERR_INIT_FAIL 初始化错误
const SEQ_ERR_INIT_FAIL = -1

// SEQ_ERR_NAME_NOTFOUND 序列名称不能为空
const SEQ_ERR_NAME_NOTFOUND = -2

// SEQ_ERR_DB_ERROR 数据库其他错误
const SEQ_ERR_DB_ERROR = -3

// SeqRes 序列暂存结果
type SeqRes struct {
	Num int
}

// Currval 序列当前值
func Currval(seq string) int {
	if seq == "" {
		return SEQ_ERR_NAME_NOTFOUND
	}

	res := SeqRes{}

	if _, err := Dao.SQL("select currval(?) as num", seq).Get(&res); err != nil {
		helper.LogError("获取"+seq+"序列失败", err)
		return SEQ_ERR_DB_ERROR
	}

	if res.Num == 0 {
		if err := newSeq(seq); err != nil {
			return SEQ_ERR_INIT_FAIL
		}

		return 1
	}

	return res.Num
}

// Nextval 序列当前值
func Nextval(seq string) int {
	if seq == "" {
		return SEQ_ERR_NAME_NOTFOUND
	}

	res := SeqRes{}

	if _, err := Dao.SQL("select nextval(?) as num", seq).Get(&res); err != nil {
		helper.LogError("获取"+seq+"序列失败", err)
		return SEQ_ERR_DB_ERROR
	}

	if res.Num == 0 {
		if err := newSeq(seq); err != nil {
			return SEQ_ERR_INIT_FAIL
		}

		return 1
	}

	return res.Num
}

// newSeq 初始化序列
func newSeq(seq string) error {
	if _, err := Dao.Exec("INSERT INTO sequence VALUES (?, ?, ?)", seq, 1, 1); err != nil {
		return helper.LogError("初始化"+seq+"序列失败", err)
	}

	return nil
}
